// 首页数据 代 
var express = require('express');
var router = express.Router();
const db = require('../../db/db');

// 首页数据
router.get('/getHomeData', function(req, res, next) {
    //消息提醒
    const warning = `SELECT COUNT(*) AS warning_count FROM nc_alarminfo`;
    // 所有牛数量
    const sqlAllCattle = `SELECT COUNT(*) AS all_cattle_count FROM nc_livestock`;
    // 在场牛数量
   const sqlPresentCattle = `SELECT COUNT(*) AS present_cattle_count FROM nc_livestock WHERE F_Isster = 1`;
    //低电量设备数量
    const sqlEartag = `SELECT COUNT(*) AS eartag_count FROM nc_device_eartag;`;
    //离线设备数量
    const sqlOffline = `SELECT COUNT(*) AS offline_count FROM nc_device_necklace;`;
    //监控设备数量
    const sqlVideo = `SELECT COUNT(*) AS video_count FROM nc_device_video;`;

    const queryWarning = () => {
        return new Promise((resolve, reject) => {
            db.query(warning, (err, result) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
    };

    const queryAllCattle = () => {
        return new Promise((resolve, reject) => {
            db.query(sqlAllCattle, (err, result) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
    };

    const queryPresentCattle = () => {
        return new Promise((resolve, reject) => {
            db.query(sqlPresentCattle, (err, result) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
    };

    const queryEartag = () => {
        return new Promise((resolve, reject) => {
            db.query(sqlEartag, (err, result) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
    };
    const queryOffline = () => {
        return new Promise((resolve, reject) => {
            db.query(sqlOffline, (err, result) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
    };
    const queryVideo = () => {
        return new Promise((resolve, reject) => {
            db.query(sqlVideo, (err, result) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
    };


    Promise.all([queryWarning(), queryAllCattle(), queryPresentCattle(), queryEartag(), queryOffline(), queryVideo()])
        .then(([warningResult, allCattleResult, presentCattleResult, eartagResult, offlineResult, videoResult]) => {
            // 提取数量
            const warningCount = warningResult[0].warning_count;
            const allCattleCount = allCattleResult[0].all_cattle_count;
            const presentCattleCount = presentCattleResult[0].present_cattle_count;
            const eartagCount = eartagResult[0].eartag_count;
            const offlineCount = offlineResult[0].offline_count;
            const videoCount = videoResult[0].video_count;

            res.send({
                code: 200,
                message: '获取成功',
                data: {
                    warning_count: warningCount,
                    allCattle_count: allCattleCount,
                    present_cattle_count: presentCattleCount,
                    eartag_count: eartagCount,
                    offline_count: offlineCount,
                    video_count: videoCount,
                }
            });
        })
        .catch(err => {
            console.error("数据库查询错误:", err);
            res.status(500).send({ code: 0, message: '获取失败', error: err.message });
        });
});





//获取低电量设备数据
router.get('/getDevices/eartag', function(req, res, next) {
    //低电量设备数量和数据
    const sql = `SELECT * FROM nc_device_eartag;`;
   db.query(sql, (err, result) =>{
    if (err) {
      res.send({ code: 0, message: '获取失败' });
      return;
    }
    else{
        res.send({ code: 200, message: '获取成功', data: result });
    }
   })
});

//获取离线设备数据
router.get('/getDevices/necklace', function(req, res, next) {
    //低电量设备数量和数据
    const sql = `SELECT * FROM nc_device_necklace;`;
   db.query(sql, (err, result) =>{
    if (err) {
      res.send({ code: 0, message: '获取失败' });
      return;
    }
    else{
        res.send({ code: 200, message: '获取成功', data: result });
    }
   })
});

// 获取监控设备数据 (分页)
router.get('/getDevices/video', function(req, res, next) {
  const page = parseInt(req.query.page) || 1; // 当前页码，默认为 1
  const pageSize = parseInt(req.query.pageSize) || 10; // 每页数量，默认为 10
  const offset = (page - 1) * pageSize; // 计算 OFFSET

  // SQL 查询监控设备数据 (分页)
  const sqlDeviceList = `
    SELECT * FROM nc_device_video
    LIMIT ? OFFSET ?
  `;

  // SQL 查询总记录数
  const sqlCount = `SELECT COUNT(*) AS total FROM nc_device_video`;
  const queryDeviceList = () => {
    return new Promise((resolve, reject) => {
      db.query(sqlDeviceList, [pageSize, offset], (err, result) => {
        if (err) {
          reject(err);
        } else {
          resolve(result);
        }
      });
    });
  };
  const queryTotalCount = () => {
    return new Promise((resolve, reject) => {
      db.query(sqlCount, (err, result) => {
        if (err) {
          reject(err);
        } else {
          const total = result[0].total;
          resolve(total);
        }
      });
    });
  };
  Promise.all([
    queryDeviceList(),
    queryTotalCount()
  ])
  .then(([deviceList, total]) => {
    res.send({
      code: 200,
      message: '获取成功',
      data: deviceList,
      page: page,
      pageSize: pageSize,
      total: total  
    });
  })
  .catch(error => {
    console.error('Error querying data: ' + error.stack);
    res.send({ code: 0, message: '获取失败', error: error });
  });
});


//养殖棚获取
router.get('/house', function(req, res, next) { 
    let sql = `select F_Title ,F_Id from nc_house`;
    console.log(sql);
    db.query(sql, (err, result) => {
        if (err) {
            res.send({ code: 0, message: '获取失败' });
            return;
        } else {
            res.send({ code: 200, message: '获取成功', data: result });
        }
    })

});
//每个养殖棚的数据
router.get('/setting', function(req, res, next) { 
    let { F_HouseId } = req.query;
     let sql = `select * from nc_setting where F_HouseId = '${F_HouseId}'`;
    console.log(sql);
    db.query(sql, (err, result) => {
        if (err) {
            res.send({ code: 0, message: '获取失败' });
            return;
        } else {
            res.send({ code: 200, message: '获取成功', data: result });
        }
    })

});

// 消息列表 (分页)
router.get('/message', function(req, res, next) {
  const page = parseInt(req.query.page) || 1; // 当前页码，默认为 1
  const pageSize = parseInt(req.query.pageSize) || 10; // 每页数量，默认为 10
  const offset = (page - 1) * pageSize; // 计算 OFFSET
  // SQL 查询消息列表 (分页)
  const sqlMessageList = `
    SELECT * FROM nc_alarminfo
    ORDER BY alarmtime DESC 
    LIMIT ? OFFSET ?
  `;
  // SQL 查询总记录数
  const sqlCount = `SELECT COUNT(*) AS total FROM nc_alarminfo`;
  const queryMessageList = () => {
    return new Promise((resolve, reject) => {
      db.query(sqlMessageList, [pageSize, offset], (err, result) => {
        if (err) {
          reject(err);
        } else {
          resolve(result);
        }
      });
    });
  };
  const queryTotalCount = () => {
    return new Promise((resolve, reject) => {
      db.query(sqlCount, (err, result) => {
        if (err) {
          reject(err);
        } else {
          const total = result[0].total;
          resolve(total);
        }
      });
    });
  };
  Promise.all([
    queryMessageList(),
    queryTotalCount()
  ])
  .then(([messageList, total]) => {
    res.send({
      code: 200,
      message: '获取成功',
      data: messageList,
      page: page,
      pageSize: pageSize,
      total: total  
    });
  })
  .catch(error => {
    console.error('Error querying data: ' + error.stack);
    res.send({ code: 0, message: '获取失败', error: error });
  });
});









module.exports = router;